from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
from functools import wraps
from django.utils.decorators import method_decorator
from .serve import *
from django.db.models import Q
import re
from django_test.settings import UPLOAD_ROOT
import os

from django.core import paginator


class Register(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        image = request.FILES.get('img')
        print(username,password,image)

        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,'',image.name),'wb')
        # 写入
        for chunk in image.chunks():
            f.write(chunk)
        f.close()

        users = Userss(username=username,password=password,img='http://127.0.0.1:8000/static/upload/'+image.name)
        users.save()
        if users:
            return Response({
                'code':200,
                'data': users.id,


            })


class AllUSerss(APIView):
    def post(self,request):
       user = Userss.objects.all()
       try:
           p = int(request.data['p'])
       except:
           p = 1
       pa = paginator.Paginator(user, 2)

       pag = pa.page(p)

       users_ser = UserssSer(pag,many=True)
       return Response({
           'data': users_ser.data,
           'list': list(pa.page_range)
       })

# 搜索
class Jian(APIView):
    def post(self,request):
        username = request.data['username']
        use = Userss.objects.filter(Q(username__icontains=username))
        js = UserssSer(use,many=True)
        return Response({
            'data': js.data
        })




# 修改
class Update(APIView):
    def post(self,request):
        id = request.data['id']
        print(id)
        u = Userss.objects.filter(id=id).first()
        data = UserssSer(u,data=request.data)
        print(data)
        if data.is_valid():
            data.save()
            return Response({
                'code': 200,
            })
        else:
            return Response({
                'code': 400
            })











